package com.samsung.utils.phone.services;

import java.util.Date;

import android.content.Context;
import android.os.Handler;

import com.samsung.utils.phone.operations.GpsOperations;
import com.samsung.utils.phone.operations.PreferenceOperations;
import com.samsung.utils.phone.primitives.GPSObject;

public class GpsServiceResult extends ServiveResult {

	GpsOperations provider = null;
	final double  minimumGap= 0.01; // about one kilometer
	

	public GpsServiceResult(Context context, PreferenceOperations prefOps,Handler mHandler) {
		super(context, prefOps,mHandler);		
		init();
	}

	@Override
	public void init() {
		provider= new GpsOperations(context);
		provider.start();
		super.init();
	}

	@Override
	public String getResultAsString() {

		String str = "";
		boolean isGPSEnabed = provider.isGPSEnabed();
		if (isGPSEnabed && provider.myLocation != null) {

			float[] oldGps = prefOps.getLastGpsLocation();
			double longiGap = Math.abs(oldGps[0] - provider.myLocation.getLongitude());
			double latiGap = Math.abs(oldGps[1] - provider.myLocation.getLatitude());
			if (! (latiGap>= minimumGap || longiGap >= minimumGap) ) {
				return null;
			}
			GPSObject objGps = new GPSObject(provider.myLocation,new Date().getTime());
			str=objGps.toString();

		} else {
			
		}
		return str;		
	}

	@Override
	public void saveValues() {

		if (hasChange && provider.myLocation!=null) {
			float[] currentLoc = { (float) provider.myLocation.getLongitude(),
					(float) provider.myLocation.getLatitude() };
			prefOps.saveGPS(currentLoc);
		}
		super.saveValues();
	}
	
	@Override
	public void destroyMe() {
		if(provider!=null){
			provider.stop();
		}
		super.destroyMe();
	}

}
